package com.ruoyi.framework.config;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.DispatcherType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ruoyi.common.filter.RepeatableFilter;
import com.ruoyi.common.filter.XssFilter;
import com.ruoyi.common.utils.StringUtils;

/**
 * Filter配置
 *
 * @author ruoyi
 */
@Configuration
public class FilterConfig
{
    @Value("${xss.enabled}")
    private String enabled;

    @Value("${xss.excludes}")
    private String excludes;

    @Value("${xss.urlPatterns}")
    private String urlPatterns;



    @SuppressWarnings({ "rawtypes", "unchecked" }) // 声明一个名为FilterConfig的Java文件
    @Bean// 告知编译器忽略特定类型的警告信息
    public FilterRegistrationBean xssFilterRegistration()// 将方法的返回对象注册为一个Bean
    {
        // 声明一个名为xssFilterRegistration的方法，返回类型为FilterRegistrationBean
        FilterRegistrationBean registration = new FilterRegistrationBean();
        // 创建一个FilterRegistrationBean对象实例
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        // 设置过滤器的调度类型为REQUEST
        registration.setFilter(new XssFilter());
        // 设置过滤器为XssFilter类的实例
        registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
        // 为过滤器添加URL模式，使用StringUtils类的split方法将urlPatterns按逗号分隔
        registration.setName("xssFilter");
        // 设置过滤器的名称为xssFilter
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        // 设置过滤器的顺序为最高优先级
        Map<String, String> initParameters = new HashMap<String, String>();
        // 创建一个Map对象，键和值的类型均为String
        initParameters.put("excludes", excludes);
        // 将excludes作为键，对应的值为excludes的值，放入initParameters中
        initParameters.put("enabled", enabled);
        // 将enabled作为键，对应的值为enabled的值，放入initParameters中
        registration.setInitParameters(initParameters);
        // 设置过滤器的初始化参数为initParameters
        return registration;
        // 返回FilterRegistrationBean对象registration
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    public FilterRegistrationBean someFilterRegistration()
    {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new RepeatableFilter());
        registration.addUrlPatterns("/*");
        registration.setName("repeatableFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }

}
